export function getItem(key) {
  const str = sessionStorage.getItem(key)
  if (isJSON(str)) {
    return JSON.parse(str)
  } else {
    return str
  }
}
export function setItem(key, val) {
  if (typeof val === 'object') {
    val = JSON.stringify(val)
  }
  return sessionStorage.setItem(key, val)
}

export function removeItem(key) {
  return sessionStorage.removeItem(key)
}

export function getLocalItem(key) {
  const str = localStorage.getItem(key)
  if (isJSON(str)) {
    return JSON.parse(str)
  } else {
    return str
  }
}
export function setLocalItem(key, val) {
  if (typeof val === 'object') {
    val = JSON.stringify(val)
  }
  return localStorage.setItem(key, val)
}

export function removeLocalItem(key) {
  return localStorage.removeItem(key)
}
function isJSON(str) {
  if (typeof str === 'string') {
    try {
      var obj = JSON.parse(str)
      if (typeof obj === 'object' && obj) {
        return true
      } else {
        return false
      }
    } catch (e) { // 普通字符串
      // console.log('error：' + str + '!!!' + e)
      return false
    }
  }
  // console.log('It is not a string!')
}

/**
 * imgToBase64
 * 获取图片 base64
 *
 * @param file {file object}
 * @returns {Promise}
 */
export async function imgToBase64 (file) {
  return new Promise(resolve => {
    let reader = new FileReader()
    reader.readAsDataURL(file)

    reader.onload = e => {
      let imgFile = e.target.result
      resolve(imgFile)
    }
  })
}

/**
 * imgToCompressed
 * 图片压缩
 * 原理就是把图片宽度、高度调小
 *
 * @param file {file object | file base64}
 * @param {width, height}：压缩图片宽高
 * @returns {Promise}
 */
export async function imgToCompressed (file, {
  width,
  height
}) {
  if (typeof file === 'object') {
    file = await imgToBase64(file)
  }

  return new Promise(resolve => {
    var image = new Image()
    image.src = file

    image.onload = () => {
      let _width = image.width
      let _height = image.height
      let canvas = document.createElement('canvas')
      let context = canvas.getContext('2d')
      let data = ''
      if (width && width > _width) {
        width = _width
        height = _height
      } else {
        // 等比例缩放
        width = width || Math.floor(_width * height / _height)
        height = height || Math.floor(width * _height / _width)
      }

      canvas.width = width
      canvas.height = height

      context.drawImage(image, 0, 0, width, height)
      data = canvas.toDataURL('image/jpeg')

      resolve(data)
    }
  })
}

/**
 * removeBase64Head
 * 切除 base64 URL 头部
 *
 * @param base64
 * @returns {String}
 */
function removeBase64Head (base64) {
  let regExp = /^data:image\/((jpeg)|(jpg)|(png));base64,/
  return base64.replace(regExp, '')
}

function percentage (arg1, arg2) {
  return new Promise((resolve, reject) => {
    if (typeof (arg1) !== 'number' || typeof (arg2) !== 'number') {
      console.log('parameter Must be a number')
      return
    }
    let t1 = 0
    let t2 = 0
    try { t1 = arg1.toString().split('.')[1].length } catch (e) {}
    try { t2 = arg2.toString().split('.')[1].length } catch (e) {}

    let r1 = Number(arg1.toString().replace('.', ''))
    let r2 = Number(arg2.toString().replace('.', ''))
    let result = (r1 / r2) * Math.pow(10, t2 - t1)
    resolve(result * 10000 / 100)
  })
}
// 求和
function accAdd (arg1, arg2) {
  var r1, r2, m
  try { r1 = arg1.toString().split('.')[1].length } catch (e) { r1 = 0 }
  try { r2 = arg2.toString().split('.')[1].length } catch (e) { r2 = 0 }
  m = Math.pow(10, Math.max(r1, r2))
  return (arg1 * m + arg2 * m) / m
}
// 乘
function accMul (arg1, arg2) {
  if (typeof (arg1) !== 'number' || typeof (arg2) !== 'number') {
    console.log('parameter Must be a number')
    return
  }
  let m = 0
  let s1 = arg1.toString()
  let s2 = arg2.toString()
  try { m += s1.split('.')[1].length } catch (e) {}
  try { m += s2.split('.')[1].length } catch (e) {}
  return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m)
}
// 除
function accDiv (arg1, arg2) {
  return new Promise((resolve, reject) => {
    // if (typeof (arg1) !== 'number' || typeof (arg2) !== 'number') {
    //   console.log('parameter Must be a number')
    //   return
    // }
    let t1 = 0
    let t2 = 0
    try { t1 = arg1.toString().split('.')[1].length } catch (e) {}
    try { t2 = arg2.toString().split('.')[1].length } catch (e) {}
    let r1 = Number(arg1.toString().replace('.', ''))
    let r2 = Number(arg2.toString().replace('.', ''))
    let result = (r1 / r2) * Math.pow(10, t2 - t1)
    resolve(result)
  })
}
const creatUuid = function () {
  return new Promise((resolve, reject) => {
    var s = []
    var hexDigits = '0123456789abcdef'
    for (var i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
    }
    s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = '-'

    var uuid = s.join('')
    resolve(uuid)
  })
}

// 格式化日期
const formatDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return [year, month, day].map(formatNumber).join('-')
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
// /**
//  * vaildRouterLegal
//  * 检验当前路由是否符合流程
//  * @param path
//  * @returns {String}
// **/
// export function vaildRouterLegal (path) {
//   console.log(path)
//   // const arr = ['address', 'scope', 'member', 'otherInfo']
//   // const pathIndex = arr.indexOf(path)
//   // for (let index = 0; index < pathIndex; index++) {
//   //   if (!getItem(arr[index])) {
//   //     return false
//   //   }
//   // }
//   // return true
// }

// 工具类大杂烩
export default {
  setLocalItem,
  getLocalItem,
  removeLocalItem,
  setItem,
  getItem,
  removeItem,
  imgToBase64,
  imgToCompressed,
  removeBase64Head,
  creatUuid,
  percentage,
  accAdd,
  accMul,
  accDiv,
  formatDate
}
